<template>
  <!-- <TagsView /> -->

  <div>
    <el-row class="header" style="margin-bottom: 10px;">
        <el-col :span="6" ></el-col>
        <el-col :span="18" align="right" >
          <el-button type="primary" @click="back">返回</el-button>
          <el-button class="ordinary" v-show="data.routeType == 'look'" @click="uploadAll()" >打包下载</el-button>
        </el-col>
    </el-row>
    <el-table
          :data="data.reportTable"
          style="width: 100%"
          v-loading="data.loading"
        >
          <el-table-column prop="number" label="序号" align="center" width="80">
            <template #default="scope">
                {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="fileName" label="附件" align="center"/>
          <el-table-column prop="companyName" label="企业名称" align="center" />
          <el-table-column prop="age" label="年度" align="center" />
          <el-table-column prop="classType" label="类型" align="center" >
            <template #default="scope">
                <el-select v-model="scope.row.classType" placeholder="请选择类型" :disabled="scope.row.id">
                    <el-option
                    v-for="item in data.classTypeOptions"
                    :key="item.itemValue"
                    :label="item.itemText"
                    :value="item.itemValue">
                    </el-option>
                </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="address" label="操作" align="center" width="240" fixed="right" style="display: flex;">
            <template #default="scope">
              <el-button type="success" @click="save(scope.row)" v-show="!scope.row.id &&  data.routeType == 'add'" style="margin-right:10px;">保存</el-button>
              <div class="file_box" @click="clickUpload(scope.$index)" v-show="!scope.row.fileName &&  data.routeType == 'add'">
                <!-- <p class="t">上传附件：        (单个附件大小限定200M内。上传成功后须点保存按钮。)</p> -->
                <el-upload class="upload-demo" :headers="headers"
                    action="/fastDfs/file/upload" multiple :before-upload="beforeAvatarUpload" :show-file-list="false"
                    :on-preview="handlePreview" :on-remove="handleRemove" :before-remove="beforeRemove" :limit="1"
                    :on-exceed="handleExceed" :on-success="handleSuccess" :on-change="handleChange">
                    <el-button type="primary">附件上传</el-button>
                    <!-- <template #tip>
                        <div class="el-upload__tip"></div>
                    </template> -->
                </el-upload>
              </div>

              <el-button @click="del(scope.row.id,scope.$index)" v-show="data.routeType == 'add'">删除</el-button>
              <el-button v-if="data.routeType == 'look'" type="primary" style="margin-left:10px;" @click="uploadItem(scope.row)">附件下载</el-button>
            </template>
          </el-table-column>
        </el-table>
    <div style="margin-top: 5px" v-show="(data.reportTable.length == 0 || data.reportTable[data.reportTable.length - 1].id) && data.routeType == 'add'">
        <el-button @click="addItem()">添加项</el-button>
    </div>
    <div style="margin-top: 5px" v-show="(data.reportTable.length == 0 || data.reportTable[data.reportTable.length - 1].id) && data.routeType == 'update'">
      <el-button @click="getupdateData()">审核</el-button>
    </div>
  </div>

</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import * as api from "../../api/eachUnit";
import { ElMessageBox, ElMessage ,UploadProps, UploadUserFile} from "element-plus";
import { useRoute ,useRouter} from "vue-router";
import pubFc from "@/views/examineManage/utils";
import * as proxy from '@/constants/proxy'
import request from '@/utils/request'
import { downloadByUrl } from '@/views/science/api/common'
import TagsView from '@/components/Layout/components/TagsView/index.vue'
import {jituanRequest} from "../../api/eachUnit";

const route = useRoute();
const router = useRouter();
const data = reactive({
    reportTable:[] as any,
    loading:false,
    uploadIndex:0,//当前上传的是第几条  用于赋值上传文件
    classTypeOptions:[] as any,//类型数据
    routeType:route.query.type
})
//返回
const back = () =>{
  ElMessageBox.confirm("确定要返回吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    router.go(-1)
  });
}
//打包下载
const uploadAll = async() =>{
/*  ElMessageBox.confirm("确定要打包下载吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {*/
    if (data.reportTable.length > 0) {
      await data.reportTable.forEach(e => {
        downloadByUrl(e.fileId, e.fileName)
      })
    } else {
      ElMessage.warning('没有可下载的报告文件')
    }
  // });
}
//下载一行
const uploadItem = async(row) =>{
   await downloadByUrl(row.fileId, row.fileName)
}
//添加一行
const addItem = () =>{
    let obj = {
        companyBankId:route.query.bankId,
        fileId:'',
        fileName:'',
        path:'',
        type:'',
        classType:'',
        companyName:route.query.name,
        age:route.query.year,
    }
    data.reportTable.push(obj)
}

const getData = () =>{
    api.lookreportRequest({companyBankId:route.query.bankId}).then(res =>{
      data.reportTable = res.data.data
      console.log('报告数据',data.reportTable);
    })
}
const getupdateData = () =>{
    api.jituanRequest({id:route.query.bankId}).then(res =>{
      if(res.data.code == 200){
        ElMessage.success('审核成功')
      }
    })
}
//保存
const save = (row) =>{
    console.log('baocun',row);
    if(row.fileName == '' || row.classType == '' ){
        ElMessage.warning('请将报告信息补充完整')
        return
    }
    api.uploadreportRequest(row).then(res =>{
        if(res.data.code == 200){
            ElMessage.success('保存成功')
            getData()
        }
    })
}
//删除
const del = (id,index) =>{
    console.log('del',id,index);
    if(id){
        api.deletereportRequest({id:id}).then(res =>{
            if(res.data.code == 200){
                ElMessage.success('删除成功')
                getData()
            }
        })
    }else{
        data.reportTable.splice(index,1)
    }
}
// 字典
const affiliation = () => {
      request({
        url: proxy.CHECC_API_CMS + '/dictItem/codelist',
        method: 'post',
        data:["KHGL_DE_COMPANY_REPORT_TYPE_CODE"]

      }).then((res) => {
        // console.log('res',res.data.data.KHGL_DE_COMPANY_REPORT_TYPE_CODE);
        data.classTypeOptions = res.data.data.KHGL_DE_COMPANY_REPORT_TYPE_CODE
      })
    }
//--------------------------附件相关----------------------------
const cookie = () => localStorage.getItem('token')
const headers =  {Authorization: 'Bearer ' + cookie()}
const clickUpload = (index) =>{
    // console.log('clickUpload',index);
    data.uploadIndex = index
}
const fileList = ref<typeof UploadUserFile[]>([])
const beforeAvatarUpload: typeof UploadProps['beforeUpload'] = (rawFile) => {
  data.loading = true
}
const handlePreview: typeof UploadProps['onPreview'] = (uploadFile) => {
  console.log('handlePreview',uploadFile)
}
const handleRemove: typeof UploadProps['onRemove'] = (file, uploadFiles) => {
  fileList.value.splice(fileList.value.indexOf(file), 1)
  console.log('handleRemove',file, uploadFiles)
}
const beforeRemove: typeof UploadProps['beforeRemove'] = (uploadFile, uploadFiles) => {
  console.log('beforeRemove')
}
const handleExceed: typeof UploadProps['onExceed'] = (files, uploadFiles) => {
  ElMessage.warning(
    `The limit is 1, you selected ${files.length} files this time, add up to ${files.length + uploadFiles.length
    } totally`
  )
}
const handleSuccess: typeof UploadProps['onSuccess'] = (res,uploadFile,fileList) => {
  console.log('handleSuccess',res,uploadFile,fileList);
  if (res.code == 200) {
    data.reportTable[data.uploadIndex] = Object.assign(data.reportTable[data.uploadIndex],res.data)

    ElMessage.success('上传成功')
    data.loading = false
  } else {
    data.loading = false
    ElMessage.error('上传失败')
  }
}
const handleChange: typeof UploadProps['onChange'] = (uploadFile, uploadFiles) => {
    //限制上传文件大小
    if (!uploadFile) return
    const isLt2M = uploadFile.size / 1024 / 1024 < 200
    if (!isLt2M) {
      ElMessage.warning(`上传文件大小不能超过 200MB!`)
      return false
    }
}

onMounted(()=>{
    getData()
    affiliation()
})
</script>

<style lang="scss" scoped>
.file_box{
    margin-right:10px;
    display: inline-block;
  }
:deep .el-upload-list .el-upload-list--text{
    display: none;
}
</style>
